//
// Copyright 2011 ReedRex Corp
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// BookDetailViewController.m
// Cloud BookShelf
//
// Created by Shunichi Takagi on 11/02/25.
//

#import "BookDetailViewController.h"


@implementation BookDetailViewController

@synthesize bookService;
@synthesize book;
@synthesize isNewBook;
@synthesize textFields;

#pragma mark -
#pragma mark Initialization

- (id) initWithBook:(Book *)aBook andService:(BookService *)aBookService {
	self = [super initWithStyle:UITableViewStyleGrouped];
	
	self.book = aBook;
	self.bookService = aBookService;
	self.isNewBook = ( aBook == nil ? YES : NO );
	
	return self;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = ( isNewBook ? @"新しい本" : book.title );
	self.textFields = [[NSMutableArray alloc] initWithCapacity:3];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"保存"
																			   style:UIBarButtonItemStylePlain
																			  target:self
																			  action:@selector(save)] autorelease];
}

- (void) save {
	((UIBarButtonItem *)self.navigationItem.rightBarButtonItem).enabled = NO;
	
	UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] init];
	ai.frame = CGRectMake(0, 0, 25, 25);
	ai.center = self.view.center;
	ai.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	[self.view addSubview:ai];
	
	[ai startAnimating];
	
	if( isNewBook ) {
		book = [[Book alloc] init];
	}
	book.title = ((UITextField *)[textFields objectAtIndex:0]).text;
	book.author = ((UITextField *)[textFields objectAtIndex:1]).text;
	book.rate = ((UITextField *)[textFields objectAtIndex:2]).text;
	
	@try {
		if( isNewBook ) {
			[bookService insert:book];
		}else{
			[bookService update:book];
		}
	}
	@catch (NSException *e) {
		UIAlertView *alert = [[UIAlertView alloc] init];
		alert.title = [e name];
		alert.message = [e reason];
		[alert addButtonWithTitle:@"確認"];
		[alert show];
	}
	
	[ai stopAnimating];
	
	[self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return ( isNewBook ? 1 : 2 );
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return ( section == 0 ? 3 : 1 );
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
    
	if( [indexPath section] == 0 ){
		UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 6, 100, 30)] autorelease];
		UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(110, 10, 150, 30)] autorelease];
		textField.returnKeyType = UIReturnKeyDone;
		textField.delegate = self;
		textField.tag = [indexPath row];
		
		[textFields insertObject:textField atIndex:[indexPath row]];
		
		if ([indexPath row] == 0) {
			label.text = @"タイトル";
			textField.text = book.title;//( book == nil ? @"" : book.title );
			textField.placeholder = @"タイトルを入力";
		} else if ([indexPath row] == 1) {
			label.text = @"著者";
			textField.text = book.author;//( book == nil ? @"" : book.author );
			textField.placeholder = @"著者を入力";
		} else if ([indexPath row] == 2) {
			label.text = @"レート";
			textField.text = book.rate;//( book == nil ? 0 : book.rate );
			textField.placeholder = @"レートを入力";
		}
		
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		[cell.contentView addSubview:label];
		[cell.contentView addSubview:textField];
	} else {
		cell.textLabel.text = @"表紙を見る／変更する";
		cell.textLabel.textAlignment = UITextAlignmentCenter;
	}
    return cell;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSLog(@"Section:%d, Row:%d", [indexPath section], [indexPath row]);

	if( [indexPath section] == 1 ) {
		BookCoverViewController *coverView = [[BookCoverViewController alloc] initWithBook:self.book andService:self.bookService];
		[self.navigationController pushViewController:coverView animated:YES];
	}
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

